package com.stud.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.stud.common.core.domain.Result;
import com.stud.common.exception.ServiceException;
import com.stud.common.mybatis.BaseServiceImpl;
import com.stud.common.utils.StringUtils;
import com.stud.system.domain.QueryConfig;
import com.stud.system.mapper.QueryConfigMapper;
import com.stud.system.service.QueryConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 简单通查Service业务层处理
 *
 * @author Stud
 * @date 2022-11-11
 */
@Slf4j
@Service
public class QueryConfigServiceImpl extends BaseServiceImpl<QueryConfigMapper, QueryConfig> implements QueryConfigService {

    @Override
    public Result queryConfigByCodeRunSQL(String queryCode, HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        QueryConfig queryConfig = check(queryCode);
        String sql = queryConfig.getQuerySql();
        List<String> sqlList = StringUtils.removeSqlTag(sql);
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            String key = "#{" + stringEntry.getKey() + "}";
            String collect = sqlList.stream().filter(
                    i -> i.contains(key)
            ).map(String::valueOf).collect(Collectors.joining());
            sql = sql.replace("[" + collect + "]", collect);
            if (sql.contains(key)) {
                //替换#{..}
                sql = sql.replace(key, stringEntry.getValue()[0]);
            }
        }
        sql = StringUtils.removeHtmlTag(sql);
        //todo case key 替换成常量
        //根据不同的return_type执行不同的语句
        switch (queryConfig.getReturnType()) {
            case "1":
                return Result.ok(SqlRunner.db().selectList(sql));
            case "2":
                Map<String, Object> objectMap = SqlRunner.db().selectOne(sql);
                if (Objects.isNull(objectMap)) {
                    return Result.fail("实体为空");
                }
                return Result.ok(objectMap);
            case "3":
                return Result.ok(SqlRunner.db().selectCount(sql));
        }
        return Result.fail();
    }


    /**
     * 检查
     */
    private QueryConfig check(String queryCode) {
        QueryConfig queryConfig = baseMapper.selectOne(new LambdaQueryWrapper<QueryConfig>().eq(QueryConfig::getQueryCode, queryCode));
        if (Objects.isNull(queryConfig)) {
            throw new ServiceException("实体为空");
        }
        return queryConfig;
    }


}
